package top.kaoshanji.p1ch06a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Comparator;
import java.util.IntSummaryStatistics;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

import static top.kaoshanji.p1ch06a.Dish.menu;

/**
 * author kaoshanji
 * ^_^
 * create time 2025/2/11 19:23
 */
public class Summarizing {

    private static final Logger logger = LogManager.getLogger(Summarizing.class);

    public static void main(String[] args) {

        // 代码清单-p1ch06a-121页a：数一数菜单里有多少种菜
        logger.info("...数一数菜单里有多少种菜...");
        System.out.println(howManyDishes());


        // 代码清单-p1ch06a-121页b：菜单中热量最高的菜
        logger.info("...菜单中热量最高的菜...");
        System.out.println(findMostCaloricDishUsingComparator());


        // 代码清单-p1ch06a-122页a：菜单列表的总热量
        logger.info("...菜单列表的总热量...");
        System.out.println(calculateTotalCalories());


        // 代码清单-p1ch06a-123页a：菜单列表的平均热量
        logger.info("...菜单列表的平均热量...");
        System.out.println(calculateAverageCalories());


        // 代码清单-p1ch06a-123页b：菜单列表的热量总和、平均值、最大值和最小值
        logger.info("...菜单列表的热量总和、平均值、最大值和最小值...");
        System.out.println(calculateMenuStatistics());


        // 代码清单-p1ch06a-123页c：菜单名称连接起来
        logger.info("...菜单名称连接起来...");
        System.out.println(getShortMenu());


        // 代码清单-p1ch06a-124页a：菜单名称连接起来，有分隔符的版本
        logger.info("...菜单名称连接起来，有分隔符的版本...");
        System.out.println(getShortMenuCommaSeparated());

    }


    private static long howManyDishes() {
        return menu.stream().collect(Collectors.counting());
    }

    private static Dish findMostCaloricDishUsingComparator() {
        Comparator<Dish> dishCaloriesComparator = Comparator.comparingInt(Dish::getCalories);
        BinaryOperator<Dish> moreCaloricOf = BinaryOperator.maxBy(dishCaloriesComparator);
        return menu.stream().collect(Collectors.reducing(moreCaloricOf)).get();
    }

    private static int calculateTotalCalories() {
        return menu.stream().collect(Collectors.summingInt(Dish::getCalories));
    }

    private static Double calculateAverageCalories() {
        return menu.stream().collect(Collectors.averagingDouble(Dish::getCalories));
    }

    private static IntSummaryStatistics calculateMenuStatistics() {
        return menu.stream().collect(Collectors.summarizingInt(Dish::getCalories));
    }

    private static String getShortMenu() {
        return menu.stream().map(Dish::getName).collect(Collectors.joining());
    }

    private static String getShortMenuCommaSeparated() {
        return menu.stream().map(Dish::getName).collect(Collectors.joining(", "));
    }



}
